package com.fjwt.gz.wxMp.offical;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.interfaces.IOfficialService;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.material.*;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.enums.WxMpApiUrl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * 微信直联公众号
 */
@Slf4j
@Service
public class OfficialWxChatService implements IOfficialService {

    //TODO  注意：这个要加WxMpService wxService，不在这里面查询，全都放在上一层查询出来之后再传进来


    /**
     * 同步公众号用户
     * @return
     */
    @Override
    public int syncFansUserInfo(Long fansId, String openid,Long userId,Long fansUserOpenId){
        return 0;
    }

    /**
     * 上传公众号素材（上传临时性素材返回信息）
     * @return
     */
    @Override
    public String uploadPicToGzh(String appid, String imgUrl ,MultipartFile file, String type,WxMpService wxService){
        try{
            log.info("请求参数：{}",appid);
            String filePath = System.getProperty("user.dir") + File.separator + "upload/"+file.getOriginalFilename();
            String path = filePath;
            File files = new File(path);
            if (!files.getParentFile().exists()) {
                files.getParentFile().mkdirs(); // 创建所有缺失的父目录
            }
            files.createNewFile(); // 创建文件
            FileCopyUtils.copy(file.getBytes(),files);
            WxMediaUploadResult result = wxService.switchoverTo(appid).getMaterialService().mediaUpload(type,files);
            if(StringUtils.isNotEmpty(result.getMediaId())){
                boolean delete = files.delete();
                if(delete){
                    log.info("删除素材文件成功，文件路径：{}",filePath);
                }else{
                    log.info("删除素材文件失败，文件路径：{}",filePath);
                }
                return result.getMediaId();
            }
            return "";
        }catch (Exception e){
            e.getMessage();
            return "";
        }
    }

    /**
     * 上传永久性图文素材
     */
    @Override
    public String uploadImgToGzh(String appid, String imgUrl, MultipartFile file, WxMpService wxService) {
        try{
            log.info("请求参数：{}",appid);
            String filePath = System.getProperty("user.dir") + File.separator + "upload/"+file.getOriginalFilename();
            String path = filePath;
            File files = new File(path);
            if (!files.getParentFile().exists()) {
                files.getParentFile().mkdirs(); // 创建所有缺失的父目录
            }
            files.createNewFile(); // 创建文件
            FileCopyUtils.copy(file.getBytes(),files);
            WxMediaImgUploadResult result =  wxService.switchoverTo(appid).getMaterialService().mediaImgUpload(files);
            if(ObjectUtil.isNotNull(result)){
                boolean delete = files.delete();
                if(delete){
                    log.info("删除素材文件成功，文件路径：{}",filePath);
                }else{
                    log.info("删除素材文件失败，文件路径：{}",filePath);
                }
                return JSONUtil.toJsonStr(result);
            }
            return "";
        }catch (Exception e){
            e.getMessage();
            return "";
        }
    }

    /**
     * 上传永久性素材
     */
    @Override
    public String uploadFileToGzh(String appid, String imgUrl, MultipartFile file, String type, WxMpService wxService) {
        try{
            log.info("请求参数：{}",appid);
            String filePath = System.getProperty("user.dir") + File.separator + "upload/"+file.getOriginalFilename();
            String path = filePath;
            File files = new File(path);
            if (!files.getParentFile().exists()) {
                files.getParentFile().mkdirs(); // 创建所有缺失的父目录
            }
            files.createNewFile(); // 创建文件
            FileCopyUtils.copy(file.getBytes(),files);
            WxMpMaterialUploadResult result =  wxService.switchoverTo(appid).getMaterialService().materialFileUpload(type,new WxMpMaterial(files.getName(),files,file.getOriginalFilename(),""));
            if(ObjectUtil.isNotNull(result.getMediaId())){
                boolean delete = files.delete();
                if(delete){
                    log.info("删除素材文件成功，文件路径：{}",filePath);
                }else{
                    log.info("删除素材文件失败，文件路径：{}",filePath);
                }
                return result.getMediaId();
            }
            return "";
        }catch (Exception e){
            e.getMessage();
            throw new BizException("上传素材失败！");
        }
    }

    /**
     * 生成渠道二维码
     * @return
     */
    @Override
    public String qrCodeCreateTmpTicket(JSONObject jsonReq, String appid,WxMpService wxService){
        log.info("生成渠道码参数：{}，公众号appid：{}",jsonReq.toJSONString(),appid);
        try{
            WxMpService service = wxService.switchoverTo(appid);
            if(Objects.isNull(service)){
                throw new BizException("公众号信息配置有误！");
            }
            WxMpQrCodeTicket codeTicket = wxService.switchoverTo(appid).getQrcodeService().qrCodeCreateTmpTicket(JSON.toJSONString(jsonReq), 2592000);
            log.info("生成渠道返回参数：{}",JSONObject.toJSONString(codeTicket));
            return JSON.toJSONString(codeTicket);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 发送客服消息
     */
    @Override
    public void sendKefuMessage(JSONObject map,String appid,WxMpService wxService){
        try{
            log.info("发送客服消息：参数{},appid:{}",JSON.toJSONString(map),appid);
            String mediaId = map.getString("mediaId");
            String openid = map.getString("openid");
            String minAppid =  map.getString("minAppid");
            WxMpKefuMessage message = new WxMpKefuMessage();
            message.setThumbMediaId(mediaId);
            message.setToUser(openid);
            message.setTitle(map.getString("title"));
            if (StringUtils.isEmpty(map.getString("eventKey"))){
                message.setMiniProgramPagePath("pages/welcome/index");
            }else {
                message.setMiniProgramPagePath("pages/welcome/index?eventKey="+map.getString("eventKey"));
            }

            message.setMiniProgramAppId(minAppid);
            message.setMsgType("miniprogrampage");
            boolean kefuMessage = wxService.switchoverTo(appid).getKefuService().sendKefuMessage(message);
            log.info("发送客服消息状态：{}",kefuMessage);
        }catch (Exception e){
            log.error("发送客服消息异常：{}",e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 发送模板消息
     * @return
     */
    @Override
    public void sendTemplateMessage(JSONObject jsonObject,String appid,WxMpService wxService)throws Exception {
        log.info("发送模板消息参数：{}，公众号appid：{}",jsonObject.toJSONString(),appid);
        String openid1 = jsonObject.getString("openid");
        WxMpTemplateMessage msg = new WxMpTemplateMessage().builder()
                .toUser(openid1)
                .templateId("hDx5Iy6fmaf8gsq4Hdo5lPeWC7HHNsR0tWke6BE5D5U")
                .miniProgram(new WxMpTemplateMessage.MiniProgram(jsonObject.getString("appid"),jsonObject.getString("pagepath"),false))
                .build();
        msg.addData(new WxMpTemplateData("thing2",jsonObject.getString("thing2")))
                .addData(new WxMpTemplateData("thing15",jsonObject.getString("thing15")))
                .addData(new WxMpTemplateData("thing5",jsonObject.getString("thing5")));
        String msgId = wxService.switchoverTo(appid).getTemplateMsgService().sendTemplateMsg(msg);
        log.info("发送模版消息返回信息：{}",msgId);
    }

    /**
     * 获取公众号用户信息
     * @return
     */
    @Override
    public boolean getUserInfo(String openid,String appid,WxMpService wxService){
        try{
            WxMpUser wxMpUser = wxService.switchoverTo(appid).getUserService().userInfo(openid);
            return wxMpUser.getSubscribe();
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 自定义公众号菜单创建
     * @return
     */
    @Override
    public String menuCreate(String json,String appid,WxMpService wxService)throws Exception{
        log.info("创建公众号菜单参数：{}，公众号appid：{}",json,appid);
        JsonObject jsonObject = GsonParser.parse(json);
        WxMpApiUrl.Menu url = WxMpApiUrl.Menu.MENU_CREATE;
        if (jsonObject.get("matchrule") != null) {
            url = WxMpApiUrl.Menu.MENU_ADDCONDITIONAL;
        }
        String result = wxService.switchoverTo(appid).post(url, json);
        log.info("创建菜单返回参数：{}",result);
        return jsonObject.get("matchrule") != null ? GsonParser.parse(result).get("menuid").getAsString() : null;
    }

    /**
     *获取openid
     * @return
     */
    @Override
    public String getOpenid(String appId, String secret, String code, WxMpService wxService) throws Exception {
        log.info("获取公众号openid参数  appid：{}, secret:{}, code:{} ",appId,secret,code);
        WxOAuth2AccessToken result = wxService.getOAuth2Service().getAccessToken(appId, secret, code);
        log.info("获取openid返回结果： {}, openid:{} ", result, result.getOpenId());
        return result.getOpenId();
    }

    /**
     * 自动回复
     * @return
     */
    @Override
    public void autoReply(String characterEncoding, String msgStr, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding(characterEncoding);
        response.getWriter().println(msgStr);
    }

    /**
     * 获取素材列表
     */
    @Override
    public WxMpMaterialFileBatchGetResult getMaterialList(String appid, String type, Integer begin, Integer end, WxMpService wxService) throws WxErrorException {
        WxMpMaterialFileBatchGetResult result = wxService.switchoverTo(appid).getMaterialService().materialFileBatchGet(type, begin, end);
        return result;
    }

    /**
     * 获取图文素材列表
     */
    @Override
    public WxMpMaterialNewsBatchGetResult getNewsMaterialList(String appid, Integer offset, Integer count, WxMpService wxService) throws WxErrorException {
        WxMpMaterialNewsBatchGetResult result = wxService.switchoverTo(appid).getMaterialService().materialNewsBatchGet(offset, count);
        return result;
    }

    /**
     * 删除素材
     */
    @Override
    public boolean deleteMaterial(String appid, String mediaId, WxMpService wxService) throws WxErrorException {
        return wxService.switchoverTo(appid).getMaterialService().materialDelete(mediaId);
    }
}
